package com.future.hedongjun.home.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.GlideUtils;
import com.future.baselib.utils.ToastUtils;
import com.future.baselib.view.IosAlertDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.home.adapter.AudioListAdapter;
import com.future.hedongjun.home.bean.AudioItem;
import com.future.hedongjun.home.bean.ClassDetail;
import com.future.hedongjun.home.bean.ClassHourBean;
import com.future.hedongjun.home.bean.response.ClassHourResponse;
import com.future.hedongjun.home.bean.response.ClassIntroduceResponse;
import com.future.hedongjun.home.service.AudioPlayService;
import com.future.hedongjun.home.utils.DES;
import com.future.hedongjun.mine.order.ConfirmClassOrderActivity;
import com.future.hedongjun.mine.ui.LoginActivity;
import com.kingsoft.media.httpcache.KSYProxyService;
import com.kingsoft.media.httpcache.OnCacheStatusListener;
import com.kingsoft.media.httpcache.OnErrorListener;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClassVoiceActivity extends BaseActivity {

    @BindView(R.id.iv_voiceIcon)
    ImageView ivVoiceIcon;
    @BindView(R.id.tv_video)
    TextView tvVideo;
    @BindView(R.id.tv_titles)
    TextView tvTitles;
    @BindView(R.id.tv_itemTitle)
    TextView tvItemTitle;
    @BindView(R.id.rv_voice)
    ListView rvVoice;
    @BindView(R.id.tvCurrentTime)
    TextView tvCurrentTime;
    @BindView(R.id.musicSeekBar)
    SeekBar musicSeekBar;
    @BindView(R.id.tvTotalTime)
    TextView tvTotalTime;
    @BindView(R.id.ivLast)
    ImageView ivLast;
    @BindView(R.id.ivPlayOrPause)
    ImageView ivPlayOrPause;
    @BindView(R.id.ivNext)
    ImageView ivNext;
    @BindView(R.id.tv_classDown)
    TextView tvVoiceDown;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    private SparseBooleanArray mBooleanArray;
    private static final String SHARED_PREFERENCES_NAME = "music_player";
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static String[] permissionArray = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
    };
    private BroadcastReceiver mEventReceiver;
    private List<Integer> mShuffleIndex;
    private int mLastPlay = -1;
    private int mLastIndex = -1;
    private boolean mIsPlaying = false;
    private boolean mIsShuffle = false;
    private int mLoopWay;
    private AudioListAdapter adapter;
    private int mDuration;
    private Object mLock = new Object();
    private boolean onDrag = false;
    private BroadcastReceiver mPlayingReceiver;
    private int mLastCheckedPosition = -1;
    private String classId;
    private List<ClassHourBean> classHourBeans;
    private String voiceUrls;
    private Intent serviceIntent;
    private String voicePath;


    /**
     * UI更新
     *
     * @param bundle 包含音乐信息的bundle
     */
    private void updateUI(Bundle bundle) {
        synchronized (mLock) {
            int duration = bundle.getInt(AudioPlayService.AUDIO_DURATION_INT, 0);
            int current = Math.min(bundle.getInt(AudioPlayService.AUDIO_CURRENT_INT, 0), duration);

            if (!onDrag) {
                int min = 0, max = musicSeekBar.getMax();
                int pos = 0;
                if (duration != 0 && (max - min) != 0) {
                    pos = (int) ((current * 1.0 / duration) * (max - min));
                }
                musicSeekBar.setProgress(pos);
            }

            int totalSecond = current / 1000;
            int minute = totalSecond / 60;
            int second = totalSecond % 60;
            if (!onDrag) {
                tvCurrentTime.setText(String.format("%02d:%02d", minute, second));
            }
            if (mDuration != duration) {
                totalSecond = (mDuration = duration) / 1000;
                minute = totalSecond / 60;
                second = totalSecond % 60;
                tvTotalTime.setText(String.format("%02d:%02d", minute, second));
            }
        }
    }

    private void saveStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(AudioPlayService.LOOP_WAY_INT, mLoopWay);
        editor.putBoolean(AudioPlayService.LIST_SHUFFLE_BOOL, mIsShuffle);
        editor.apply();
    }

    private void readStatus() {
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE);
        mLoopWay = sharedPreferences.getInt(AudioPlayService.LOOP_WAY_INT, AudioPlayService.LIST_NOT_LOOP);
        mIsShuffle = sharedPreferences.getBoolean(AudioPlayService.LIST_SHUFFLE_BOOL, false);
    }

    private Intent getAudioIntent(String voiceUrl) {
        Intent intent = new Intent();
        intent.putExtra(AudioPlayService.AUDIO_PATH_STR, voiceUrl);
        intent.putExtra(AudioPlayService.AUDIO_CURRENT_INT, 0);
        return intent;
    }

    private void playAudio(int position) {
        playAudio(position, true, false, false);
    }

    /**
     * @param position 在原始音乐列表的位置
     * @param shuffle  是否再次打乱顺序
     */
    private void playAudio(int position, boolean start, boolean shuffle, boolean forced) {
        if (forced || position != mLastPlay) {
            String voiceUrl = DES.decode(classHourBeans.get(position).mpaddress);
            serviceIntent = getAudioIntent(voiceUrl);
            serviceIntent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.PLAY_ACTION);
            serviceIntent.putExtra(AudioPlayService.AUDIO_PLAY_NOW_BOOL, start);
            serviceIntent.setClass(this, AudioPlayService.class);
            mLastPlay = position;
            enableButton(false);
            setItemChecked(position);
            startService(serviceIntent);
        }
    }

    private void playAudio(boolean start) {
        if (voicePath != null) {
            serviceIntent = getAudioIntent(voicePath);
        }
        serviceIntent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.PLAY_ACTION);
        serviceIntent.putExtra(AudioPlayService.AUDIO_PLAY_NOW_BOOL, start);
        serviceIntent.setClass(this, AudioPlayService.class);
        enableButton(true);
        startService(serviceIntent);
    }

    /**
     * 歌曲切换
     *
     * @param next     是否为下一首
     * @param fromUser 是否来自用户的动作
     */
    private void musicChange(boolean next, boolean fromUser) {
        if (mLoopWay == AudioPlayService.AUDIO_REPEAT && !fromUser) {
            playAudio(mLastPlay, true, false, true);
        } else {
            int index;
            if (mIsShuffle) {
                int listSize = mShuffleIndex.size();
                if (next) {
                    index = mShuffleIndex.get(mLastIndex = (mLastIndex + 1) % listSize);
                } else {
                    index = mShuffleIndex.get(
                            mLastIndex = (mLastIndex - 1 + listSize) % listSize);
                }
                mLastIndex = index;
            } else {
                int listSize = classHourBeans.size();
                if (next) {
                    index = (mLastPlay + 1) % listSize;
                } else {
                    index = (mLastPlay - 1 + listSize) % listSize;
                }
            }
            if (index == 0 && next && !fromUser && mLoopWay == AudioPlayService.LIST_NOT_LOOP) {
                playAudio(index, false, mIsShuffle, true);
            } else {
                playAudio(index, mIsPlaying, true, true);
            }
        }
    }

    /**
     * 初始化列表
     */
    private void init() {
        if (TextUtils.isEmpty(MyApp.getInstance().getUserToken())) {
            startActivity(new Intent(ClassVoiceActivity.this, LoginActivity.class));
        } else {
            new HttpRequest<ClassHourResponse>()
                    .with(this)
                    .setApiCode("_classdetail_001")
                    .addParam("id", classId)
                    .addParam("userToken", MyApp.getInstance().getUserToken())
                    .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            classHourBeans = ((ClassHourResponse) response).data;
                            mBooleanArray = new SparseBooleanArray(classHourBeans.size());
                            adapter = new AudioListAdapter(ClassVoiceActivity.this, R.layout.recycler_item_class_hour, classHourBeans, mBooleanArray);
                            rvVoice.setAdapter(adapter);
                            for (int i = 0; i < classHourBeans.size(); i++) {
                                if (DES.decode(classHourBeans.get(i).mpaddress).equals(voiceUrls)) {
                                    playAudio(i);
                                }
                            }
                        }
                    }).start(new ClassHourResponse());
        }

        rvVoice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (classHourBeans.get(position).buy_status.equals("3")) {
                    setItemChecked(position);
                    playAudio(position, true, false, false);
                } else {
                    new IosAlertDialog(ClassVoiceActivity.this)
                            .builder()
                            .setMsg("请先购买课程后,才能实用哟!")
                            .setNegativeButton("考虑一下", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setPositiveButton("立即购买", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (classHourBeans != null) {
                                        ClassDetail detail = new ClassDetail();
                                        detail.setId(classHourBeans.get(position).id);
                                        detail.setName(classHourBeans.get(position).ClassName);
                                        detail.setLogo_img(classHourBeans.get(position).classLogo);
                                        double price = 0;
                                        try {
                                            price = Double.valueOf(classHourBeans.get(position).classPrice);
                                        } catch (NumberFormatException e) {

                                        }
                                        detail.setPrice(price);
                                        ConfirmClassOrderActivity.open(ClassVoiceActivity.this, detail);
                                    }

                                }
                            }).show();
                }
            }
        });
    }

    private void pause() {
        if (mLastPlay >= 0) {
            Intent intent = new Intent(ClassVoiceActivity.this, AudioPlayService.class);
            if (mIsPlaying) {
                intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.PAUSE_ACTION);
            } else {
                intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.REPLAY_ACTION);
            }
            enableButton(false);
            startService(intent);
        }
    }

    private void CachePause() {
        Intent intent = new Intent(ClassVoiceActivity.this, AudioPlayService.class);
        if (mIsPlaying) {
            intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.PAUSE_ACTION);
        } else {
            intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.REPLAY_ACTION);
        }
        enableButton(false);
        startService(intent);
    }

    private void enableButton(boolean enable) {
        enableButton(enable, false);
    }

    private void enableButton(boolean enable, boolean grey) {
        ivPlayOrPause.setEnabled(enable);
        ivPlayOrPause.setEnabled(enable);
        ivNext.setEnabled(enable);
//        if (grey && !enable) {
//            ivPlayOrPause.setBackgroundResource(R.drawable.bofang);
//        } else {
//            ivPlayOrPause.setBackgroundResource(R.drawable.zanting);
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_voice);
        ButterKnife.bind(this);
        classId = getIntent().getStringExtra("classId");
        voiceUrls = getIntent().getStringExtra("voiceUrl");
        voicePath = getIntent().getStringExtra("voicePath");
        if (voicePath!=null) {
            playAudio(true);
            tvVoiceDown.setVisibility(View.GONE);
        }else {
            tvVoiceDown.setVisibility(View.VISIBLE);
        }
        setTitle("课程详情");
        getData();
        readStatus();
        enableButton(false, true);
        // 事件广播接受器
        LocalBroadcastManager.getInstance(this).registerReceiver(mEventReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String event = intent.getStringExtra(AudioPlayService.EVENT_KEY);
                if (event == null) {
                    return;
                }
                switch (event) {
                    case AudioPlayService.FINISHED_EVENT:
                        musicChange(true, false);
                        break;
                    case AudioPlayService.NEXT_EVENT:
                        if (voicePath != null) {
                            ToastUtils.longToast(mContext, "沒有更多了!");
                        } else {
                            musicChange(true, true);
                        }
                        break;
                    case AudioPlayService.PREVIOUS_EVENT:
                        if (voicePath != null) {
                            ToastUtils.longToast(mContext, "沒有更多了!");
                        } else {
                            musicChange(false, true);
                        }
                        break;
                    case AudioPlayService.PLAY_EVENT:
                        boolean isPlay = intent.getBooleanExtra(AudioPlayService.AUDIO_PLAY_NOW_BOOL, false);
                        if (isPlay) {
                            ivPlayOrPause.setImageResource(R.drawable.zanting);
                            mIsPlaying = true;
                        } else {
                            ivPlayOrPause.setImageResource(R.drawable.bofang);
                            mIsPlaying = false;
                        }
                        enableButton(true);
                        break;
                    case AudioPlayService.PAUSE_EVENT:
                        ivPlayOrPause.setImageResource(R.drawable.bofang);
                        mIsPlaying = false;
                        enableButton(true);
                        break;
                    case AudioPlayService.REPLAY_EVENT:
                        ivPlayOrPause.setImageResource(R.drawable.zanting);
                        mIsPlaying = true;
                        enableButton(true);
                        break;
                    case AudioPlayService.LIST_ORDER_EVENT:
                        mIsShuffle = intent.getBooleanExtra(AudioPlayService.LIST_SHUFFLE_BOOL, true);
                        saveStatus();
                        break;
                    case AudioPlayService.CHANGE_LOOP_EVENT:
                        mLoopWay = intent.getIntExtra(
                                AudioPlayService.LOOP_WAY_INT, AudioPlayService.LIST_NOT_LOOP);
                        saveStatus();
                        break;
                }
            }
        }, new IntentFilter(AudioPlayService.BROADCAST_EVENT_FILTER));
        // 权限分配
        List<String> requestList = new ArrayList<>();
        for (String permission : permissionArray) {
            if (ActivityCompat.checkSelfPermission(this, permission)
                    != PermissionChecker.PERMISSION_GRANTED) {
                requestList.add(permission);
            }
        }
        if (requestList.size() > 0) {
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[]{}),
                    PERMISSION_REQUEST_CODE);
        } else {
            init();
        }
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int min = 0, max = seekBar.getMax();
                    int changedCurrent = (int) (mDuration * 1.0 / (max - min) * progress);
                    int totalSecond = changedCurrent / 1000;
                    int minute = totalSecond / 60;
                    int second = totalSecond % 60;
                    tvCurrentTime.setText(String.format("%02d:%02d", minute, second));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                synchronized (mLock) {
                    onDrag = true;
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int min = 0, max = seekBar.getMax();
                int changedCurrent = (int) (mDuration * 1.0 / (max - min) * seekBar.getProgress());
                seekMusic(changedCurrent);
                synchronized (mLock) {
                    onDrag = false;
                }
            }
        });
        // 更新UI广播
        LocalBroadcastManager.getInstance(this).registerReceiver(mPlayingReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateUI(intent.getExtras());
            }
        }, new IntentFilter(AudioPlayService.BROADCAST_PLAYING_FILTER));
    }


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
    }


    @OnClick({R.id.tv_video, R.id.ivLast, R.id.ivPlayOrPause, R.id.ivNext, R.id.tv_classDown})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_video:
                Intent intent = new Intent(this, ClassDetailActivity.class);
                intent.putExtra("id", classId);
                startActivity(intent);
                break;
            case R.id.ivLast:
                previousMusic();
                break;
            case R.id.ivPlayOrPause:
                if (voicePath != null) {
                    CachePause();
                } else {
                    pause();
                }
                break;
            case R.id.ivNext:
                if (voicePath != null) {
                    ToastUtils.longToast(mContext, "沒有更多了!");
                } else {
                    musicChange(true, true);
                }
                break;
            case R.id.tv_classDown:
                ToastUtils.longToast(this, "开始缓存");
                KSYProxyService mProxyService = MyApp.getKSYProxy(this);
                mProxyService.registerErrorListener(mOnErrorListener);
                mProxyService.setMaxFilesCount(500);
                mProxyService.setCacheRoot(new File(Environment.getExternalStorageDirectory().toString() + File.separator + "CacheFile" + "/" + "CacheVoice" + "/" + classHourBeans.get(0).ClassName + "####" + classHourBeans.get(0).classId+"----"+classHourBeans.get(0).classLogo));
                mProxyService.startServer();
                for (int i = 0; i < classHourBeans.size(); i++) {
                    mProxyService.startPreDownload(DES.decode(classHourBeans.get(i).mpaddress));
                    mProxyService.registerCacheStatusListener(mCacheStatusListener, DES.decode(classHourBeans.get(i).mpaddress));
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this, AudioPlayService.class));
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mEventReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mPlayingReceiver);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                boolean good = true;
                for (int i = 0; i < permissions.length; ++i) {
                    if (grantResults[i] != PermissionChecker.PERMISSION_GRANTED) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ClassVoiceActivity.this);
                        builder.setTitle("提示").setMessage("不允许读取SD卡权限则无法正常使用哦")
                                .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ClassVoiceActivity.super.finish();
                                    }
                                }).show();
                        good = false;
                        break;
                    }
                }
                if (good) {
                    init();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mIsPlaying) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    AlertDialog dialog = builder.setTitle("音乐正在播放")
                            .setPositiveButton("后台播放", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ClassVoiceActivity.this.finish();
                                }
                            })
                            .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ClassVoiceActivity.super.finish();
                                }
                            }).create();

                    dialog.show();
                } else {
                    super.finish();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 下一首
    private void nextMusic() {
        Intent intent = new Intent(this, AudioPlayService.class);
        intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.NEXT_ACTION);
        startService(intent);
    }

    // 上一首
    private void previousMusic() {
        Intent intent = new Intent(this, AudioPlayService.class);
        intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.PREVIOUS_ACTION);
        startService(intent);
    }

    // seek歌曲
    private void seekMusic(int seekTo) {
        Intent intent = new Intent(ClassVoiceActivity.this, AudioPlayService.class);
        intent.putExtra(AudioPlayService.ACTION_KEY, AudioPlayService.SEEK_ACTION);
        intent.putExtra(AudioPlayService.AUDIO_SEEK_POS_INT, seekTo);
        startService(intent);
    }

    /**
     * @param position
     */
    public void setItemChecked(int position) {
        if (mLastCheckedPosition == position)
            return;

        mBooleanArray.put(position, true);

        if (mLastCheckedPosition > -1) {
            mBooleanArray.put(mLastCheckedPosition, false);
            // adapter.notifyDataSetChanged(mLastCheckedPosition);
        }

        adapter.notifyDataSetChanged();
        mLastCheckedPosition = position;
    }

    public void getData() {
        if (TextUtils.isEmpty(MyApp.getInstance().getUserToken())) {
            startActivity(new Intent(ClassVoiceActivity.this, LoginActivity.class));
        } else {
            new HttpRequest<ClassIntroduceResponse>()
                    .with(this)
                    .setApiCode("_classdetail_001")
                    .addParam("id", classId)
                    .addParam("userToken", MyApp.getInstance().getUserToken())
                    .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            tvTitles.setText(((ClassIntroduceResponse) response).data.get(0).name);
                            GlideUtils.loadImage(ClassVoiceActivity.this, ((ClassIntroduceResponse) response).data.get(0).imgUrl, ivVoiceIcon);
                        }
                    }).start(new ClassIntroduceResponse());
        }
    }

    private OnCacheStatusListener mCacheStatusListener = new OnCacheStatusListener() {
        @Override
        public void OnCacheStatus(String url, long sourceLength, int percentsAvailable) {
            ToastUtils.longToast(ClassVoiceActivity.this, percentsAvailable + "%");
//            if (percentsAvailable == 100) {
//                tvProgress.setText("已缓存");
//            } else {
//                tvProgress.setText(percentsAvailable + "%");
//            }
        }
    };

    private OnErrorListener mOnErrorListener = new OnErrorListener() {
        @Override
        public void OnError(int errCode) {
            Toast.makeText(ClassVoiceActivity.this, "HttpCache meet an error:" + errCode, Toast.LENGTH_SHORT).show();
        }
    };
}